package tr.com.netgis;

import tr.com.netgis.db.NGDbHelper;
import tr.com.netgis.db.NGDbHelper.Table;
import tr.com.netgis.pojo.Message;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class CustomSqlCursorAdapter extends SimpleCursorAdapter implements
		OnClickListener {

	private Context context;

	private NGDbHelper dbHelper;
	private Cursor currentCursor;
	private LayoutInflater inflater;

	public CustomSqlCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, NGDbHelper dbHelper) {
		super(context, layout, c, from, to);
		this.currentCursor = c;
		this.context = context;
		this.dbHelper = dbHelper;
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}
	
	@Override
	public boolean hasStableIds() {
		return true;
	}

	public View getView(int pos, View inView, ViewGroup parent) {
		// This is how you would determine if this particular item is checked
		// when the view gets created
		// --
		// final ListView lv = (ListView) parent;
		// final boolean isChecked = lv.isItemChecked(position);

		// The item we want to get the view for
		// --
		this.currentCursor.moveToPosition(pos);
		final Message item = NGDbHelper.getMessage(this.currentCursor);

		// Re-use the view if possible
		// --
		View v = inView;
		if (v == null) {
			v = inflater.inflate(R.layout.messages_row, null);
		}

		// Set some view properties (We should use the view holder pattern in
		// order to avoid all the findViewById and thus improve performance)
		// --
		final TextView idView = (TextView) v.findViewById(R.id.itemId);
		if (idView != null) {
			idView.setText("#" + item.get_id());
		}

		final TextView captionView = (TextView) v
				.findViewById(R.id.itemCaption);
		if (captionView != null) {
			captionView.setText(item.getMessageHeader());
		}
		
		return (v);
	}

	public void ClearSelections() {
		this.dbHelper.clearSelections(Table.MESSAGES);
		this.currentCursor.requery();
	}

	@Override
	public void onClick(View v) {

		CheckBox cBox = (CheckBox) v;
		Integer _id = (Integer) cBox.getTag();

		ContentValues values = new ContentValues();
		values.put(" selected", cBox.isChecked() ? 1 : 0);
		
		this.dbHelper.getWritableDatabase().update(NGDbHelper.TABLE_NAME_MESSAGES, values, "_id=?",
				new String[] { Integer.toString(_id) });
				
	}

}